package com.zb.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zb.entity.SelectVo;
import com.zb.entity.ZjAccount;
import com.zb.entity.ZjWorkTeam;
import com.zb.entity.ZjWorkTeamEmp;
import com.zb.order.service.ConWorkSetService;
import com.zb.result.PageUtil;
import com.zb.service.ZjAccountService;
import com.zb.service.ZjWorkTeamEmpService;
import com.zb.service.ZjWorkTeamService;
import com.zb.vo.WorkTeamListVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author WEN
 * @Date 2023/9/12 0012
 **/
@Service
public class ConWorkSetServiceImpl implements ConWorkSetService {
    @Resource
    private ZjWorkTeamService workTeamService;
    @Resource
    private ZjWorkTeamEmpService workTeamEmpService;
    @Resource
    private ZjAccountService accountService;

    // 获取客服组列表
    @Override
    public Map<String, Object> getList(Long custAccId, SelectVo selectVo) {
        QueryWrapper<ZjWorkTeam> wrapper = new QueryWrapper<>();
        wrapper.select("id", "name", "emp_id", "load_num", "is_disabled AS disabled", "gmt_create", "gmt_update");
        wrapper.eq("cust_acc_id", custAccId);
        if (StringUtils.isNotBlank(selectVo.getName())) {
            wrapper.like("name", selectVo.getName());
        }
        PageUtil.setPageLimit(selectVo);
        Page<ZjWorkTeam> page = workTeamService.page(new Page<>(selectVo.getPage(), selectVo.getLimit()), wrapper);

        List<Long> workTeamIds = page.getRecords().stream().map(ZjWorkTeam::getId).toList();
        List<ZjWorkTeamEmp> teamEmps = workTeamEmpService.getByWorkTeamIds(workTeamIds);
        List<ZjAccount> accounts = accountService.getByIds(new ArrayList<>(teamEmps.stream().map(ZjWorkTeamEmp::getEmpId).collect(Collectors.toSet())));

        List<WorkTeamListVo> voList = page.getRecords().stream().map(team -> {
            WorkTeamListVo vo = new WorkTeamListVo();
            BeanUtils.copyProperties(team, vo);
            vo.setStatus(team.getDisabled());
            vo.setCreateTime(team.getGmtCreate());
            vo.setUpdateTime(team.getGmtUpdate());
            vo.setEmps(teamEmps.stream().filter(emp -> Objects.equals(team.getId(), emp.getWorkTeamId())).map(teamEmp -> {
                return accounts.stream().filter(ac -> Objects.equals(teamEmp.getEmpId(), ac.getId())).map(ZjAccount::getName).findFirst().orElse("");
            }).toList());
            return vo;
        }).toList();
        return PageUtil.pageList(page.getCurrent(), page.getSize(), page.getTotal(), voList);
    }
}
